package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.RecommendUser;
import com.itheima.service.mongo.RecommendUserService;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class RecommendUserServiceImpl implements RecommendUserService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public RecommendUser findTodayBest(Long toUserId) {
        //1.创建条件查询对象(toUserId,分页,排序)
        Query query = new Query(Criteria.where("toUserId").is(toUserId))
                .with(Sort.by(Sort.Order.desc("score"))).limit(1);

        //2.查询推荐用户表,返回数据
        return mongoTemplate.findOne(query,RecommendUser.class);
    }

    @Override
    public PageBeanVo findByPage(Long toUserId, Integer pageNum, Integer pageSize) {
        //1.创建条件对象(toUserId)
        Query query = new Query(Criteria.where("toUserId").is(toUserId));

        //2.查询推荐表中总条数
        long count = mongoTemplate.count(query, RecommendUser.class);

        //3.追加分页和排序条件,跳过今日佳人
        query.with(Sort.by(Sort.Order.desc("score")))
                .skip((pageNum-1)*pageSize+1).limit(pageSize);

        //4.查询推荐表中当前页的数据
        /*
            若推荐用户只有一个count=1(就是今日佳人),但是list中没有数据
            最好再处理下count
         */
        List<RecommendUser> recommendUsers = mongoTemplate.find(query, RecommendUser.class);

        if (count>1) {
            count = count - 1 ;
        }else {
            count = 0;
        }

        //5.封装pageBeanVo且返回
        return new PageBeanVo(pageNum,pageSize,count,recommendUsers);
    }

    @Override
    public RecommendUser findPersonalInfo(Long toUserId, Long jiaRenId) {
        //1.创建条件对象
        Query query = new Query(Criteria.where("toUserId").is(toUserId).and("userId").is(jiaRenId));
        //2.查询推荐用户表获取数据
        return mongoTemplate.findOne(query,RecommendUser.class);
    }


    @Override
    public List<RecommendUser> findByToUserId(Long toUserId) {
        //1.创建条件对象(俩id)
        Query query = new Query(Criteria.where("toUserId").is(toUserId));
        //2.查找推荐表,返回推荐用户集合
        return mongoTemplate.find(query, RecommendUser.class);
    }

    @Override
    public void remove(Long toUserId, Long recommendUserId) {
        //1.创建条件对象(俩id)
        Query query = new Query(Criteria.where("toUserId").is(toUserId).and("userId").is(recommendUserId));
        //2.从该表中删除数据
        mongoTemplate.remove(query,RecommendUser.class);
    }
}
